package com.scu.bank.util;

import com.scu.bank.constants.JwtConstants;
import com.scu.bank.core.exception.AuthException;
import com.scu.bank.core.jwt.JwtInfo;
import io.jsonwebtoken.*;
import org.joda.time.DateTime;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @author: pmeng
 * @Date: 2019/1/13 22:37
 * @Description: 生成token的工具类
 */
public class JwtTokenUtils {

    private static Key getKeyInstance(){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary("mall-user");
        return new SecretKeySpec(bytes,signatureAlgorithm.getJcaName());
    }

    /**
     * 生成token的方法
     * @param jwtInfo
     * @param expire
     * @return
     */
    public static String generatorToken(JwtInfo jwtInfo, int expire){
        return Jwts.builder()
                .claim(JwtConstants.JWT_KEY_USER_ID,jwtInfo.getUid())
                .claim(JwtConstants.JWT_KEY_EXPIRE_TIME, DateUtil.addDate(new Date(),expire))
                .claim(JwtConstants.JWT_KEY_USER_NAME, jwtInfo.getUserName())
                .claim(JwtConstants.JWT_KEY_USER_PROFILE, jwtInfo.getProfile())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.HS256,getKeyInstance()).compact();
    }

    /**
     * 根据token获取token中的信息
     * @param token
     * @return
     */
    public static JwtInfo getTokenInfo(String token){
        Claims claims= null;
        try {
            claims = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e1){
            // token过期
            claims =e1.getClaims();
            throw new AuthException("token 失效,请重新登录!");
        }

        String uid = claims.get(JwtConstants.JWT_KEY_USER_ID).toString();
        String userName = claims.get(JwtConstants.JWT_KEY_USER_NAME).toString();
        String userProfile = claims.get(JwtConstants.JWT_KEY_USER_PROFILE).toString();
        Date expireTime = new Date();
        expireTime.setTime(Long.valueOf(claims.get(JwtConstants.JWT_KEY_EXPIRE_TIME).toString()));

        if (new Date().getTime() > expireTime.getTime()){
            throw new AuthException("token 失效,请重新登录!");
        }

        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setUid(uid);
        jwtInfo.setExpireTime(expireTime);
        jwtInfo.setUserName(userName);
        jwtInfo.setUserName(userProfile);

        return jwtInfo;
    }
}